package com.mjk.common.util;

import com.google.gson.internal.LinkedTreeMap;
import lombok.Getter;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

import java.util.Map;

public class DynamicBean {
	/**
	 * 目标对象
     * -- GETTER --
     *  获取对象

     */
	@Getter
    private final Object target;
	/**
	 * 属性集合
	 */
	private final BeanMap beanMap;

	@SuppressWarnings("rawtypes")
	public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
		this.target = generateBean(superclass, propertyMap);
		this.beanMap = BeanMap.create(this.target);
	}

	/**
	 * bean 添加属性和值
	 *
     */
	public void setValue(String property, Object value) {
		if(value instanceof LinkedTreeMap map) {
			if(map.isEmpty()) {
				return;
			}
		}
		beanMap.put(property, value);
	}

	/**
	 * 获取属性值
	 *
     */
	public Object getValue(String property) {
		return beanMap.get(property);
	}

    /**
	 * 根据属性生成对象
	 *
     */
	@SuppressWarnings("rawtypes")
	private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
		BeanGenerator generator = new BeanGenerator();
		if (null != superclass) {
			generator.setSuperclass(superclass);
		}
		BeanGenerator.addProperties(generator, propertyMap);
		return generator.create();
	}

}
